package com.fyakm.daodejing.simple.stockTest.service;

import com.fyakm.daodejing.simple.stockTest.domain.Investors;
import com.fyakm.daodejing.simple.stockTest.domain.StockEntity;
import com.fyakm.daodejing.simple.stockTest.domain.StockHistory;

import java.util.List;

public class TradingSimulator {

    /**
     * 模拟交易
     *
     * @param investor 股民
     * @param stock    股票
     * @param history  股票历史数据
     */
    public static void simulateTrading(Investors investor, StockEntity stock, List<StockHistory> history) {
        for (StockHistory record : history) {
            String action = TradingAlgorithm.decideAction(record);
            String stockCode = record.getCode();
            double price = record.getClose();

            switch (action) {
                case "BUY":
                    buyStock(investor, stockCode, 100, price,record); // 每次买入 100 股
                    break;
                case "SELL":
                    sellStock(investor, stockCode, 100, price,record); // 每次卖出 100 股
                    break;
                case "HOLD":
                    // 不操作
                    break;
            }
        }
    }

    private static void buyStock(Investors investor, String stockCode, int quantity, double price,StockHistory history) {
        double totalCost = quantity * price;
        if (investor.getMoney() >= totalCost) {
            investor.setMoney((int) (investor.getMoney() - totalCost));
            investor.getStockMap().put(stockCode, investor.getStockMap().getOrDefault(stockCode, 0) + quantity);
//            System.out.println(investor.getName() + "买入 " + stockCode + " " + quantity + " 股，价格：" + price);

            // 输出买入信息
            System.out.println("买入 " + stockCode + " " + quantity + " 股，价格：" + price +",日期" + history.getDate()+ ",涨跌幅"+history.getPctChg());

        } else {
            System.out.println("现金不足，无法买入 " + stockCode);
        }
    }

    private static void sellStock(Investors investor, String stockCode, int quantity, double price,StockHistory history) {
        int currentQuantity = investor.getStockMap().getOrDefault(stockCode, 0);
        if (currentQuantity >= quantity) {
            investor.setMoney((int) (investor.getMoney() + quantity * price));
            investor.getStockMap().put(stockCode, currentQuantity - quantity);
//            System.out.println("卖出 " + stockCode + " " + quantity + " 股，价格：" + price);

            System.out.println("卖出 " + stockCode + " " + quantity + " 股，价格：" + price +",日期" + history.getDate()+ ",涨跌幅"+history.getPctChg());
        } else {
            System.out.println("持股不足，无法卖出 " + stockCode);
        }
    }
}